package com.tsd.core.mybatis;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * <columnOverride column="ids" javaType="java.lang.Integer[]" typeHandler="com.tsd.core.mybatis.JsonIntegerArrayTypeHandler"/>
 *
 * @author Hillpool
 */
public class JsonIntegerArrayTypeHandler extends BaseTypeHandler<Integer[]> {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    public static final Logger LOGGER = LoggerFactory.getLogger(JsonIntegerArrayTypeHandler.class);

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Integer[] parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, toJson(parameter));
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.toObject(rs.getString(columnName));
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getString(columnIndex));
    }

    @Override
    public Integer[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getString(columnIndex));
    }

    private String toJson(Integer[] params) {
        if (params != null) {
            try {
                return MAPPER.writeValueAsString(params);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return "[]";
    }

    private Integer[] toObject(String content) {
        if (content != null && !content.isEmpty()) {
            try {
                return MAPPER.readValue(content, Integer[].class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }
}